package com.infore.dataReceiving.quartz;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.infore.dataReceiving.entity.CheckData;
import com.infore.dataReceiving.entity.EquipmentInfo;
import com.infore.dataReceiving.entity.HourData;
import com.infore.dataReceiving.entity.RealEquipmentInfo;
import com.infore.dataReceiving.entity.RealTimeData;
import com.infore.dataReceiving.entity.RecoveryData;
import com.infore.dataReceiving.entity.SpanCheckData;
import com.infore.dataReceiving.entity.ZeroCheckData;
import com.infore.dataReceiving.repository.ICheckDataRepository;
import com.infore.dataReceiving.repository.IEquipmentInfoRepository;
import com.infore.dataReceiving.repository.IHourDataRepository;
import com.infore.dataReceiving.repository.IRealEquipmentInfoRepository;
import com.infore.dataReceiving.repository.IRealTimeDataRepository;
import com.infore.dataReceiving.repository.IRecoveryDataRepository;
import com.infore.dataReceiving.repository.ISpanCheckDataRepository;
import com.infore.dataReceiving.repository.IZeroCheckDataRepository;
import com.infore.dataReceiving.repository.batch.IDataBatchRepository;
import com.infore.dataReceiving.util.RedisUtil;



@Component
public class Water2018ScheduledTasks{
	
	private static final Logger logger = LoggerFactory.getLogger(Water2018ScheduledTasks.class);
	private static Map<String, String> stationMap = new HashMap<String, String>();
	
	@Autowired
    private RedisUtil redisUtil;
	
	@Autowired
	private IRealTimeDataRepository iRealTimeDataRepository;
	
	@Autowired
	private IHourDataRepository iHourDataRepository;
	
	@Autowired
	private ICheckDataRepository iCheckDataRepository;
	
	@Autowired
	private IRecoveryDataRepository iRecoveryDataRepository;
	
	@Autowired
	private IZeroCheckDataRepository iZeroCheckDataRepository;
	
	@Autowired
	private ISpanCheckDataRepository iSpanCheckDataRepository;
	
	@Autowired
	private IEquipmentInfoRepository iEquipmentInfoRepository;
	
	@Autowired
    private IRealEquipmentInfoRepository iRealEquipmentInfoRepository;

	
	@Autowired
    private IDataBatchRepository<RealEquipmentInfo> iDataBatchRepository;
	
	
	public void GetGJZMNList(){
		
		
	}
	
	
	public void GetWaterRealTimeData(){
//		List<Object> list = redisUtil.lGet("realData",0,-1);
//		int size = list.size();
//		if(size>0) {
//			List<RealTimeData> list = new ArrayList<>();
			if(redisUtil==null) {
				System.out.println("redis为空，请联系管理员！");
				logger.error("redis为空，请联系管理员！");
				return;
			}
			while(redisUtil.lGetListSize("realData")>0) {
				RealTimeData data = (RealTimeData)redisUtil.leftPop("realData");
				String msg = "mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime();
				if(stationMap.get(msg)==null) {
					stationMap.put(msg, "1");
				}else {
					System.out.println("丢弃重复数据");
					continue;
				}
				System.out.println("获取到实时数据MN："+data.getMn());
				try {
					iRealTimeDataRepository.saveAndFlush(data);
				} catch (Exception e) {
					System.out.println("重复实时数据："+msg);
					logger.error("重复实时数据："+msg);
				}
//				list.add(data);
			}
			stationMap = new HashMap<String, String>();
//			iRealTimeDataRepository.saveAll(list);
//		}
	}
	
	public void GetWaterHourData(){
//		List<HourData> list = new ArrayList<>();
		if(redisUtil==null) {
			System.out.println("redis为空，请联系管理员！");
			logger.error("redis为空，请联系管理员！");
			return;
		}
		while(redisUtil.lGetListSize("hourData")>0) {
			HourData data = (HourData)redisUtil.leftPop("hourData");
			System.out.println("获取到小时数据MN："+data.getMn());
			try {
				iHourDataRepository.saveAndFlush(data);
			} catch (Exception e) {
				System.out.println("重复小时数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
				logger.error("重复小时数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
			}
//			list.add(data);
		}
//		iHourDataRepository.saveAll(list);
	}
	
	public void GetWaterQualityControlData(){
		GetWaterCheckData();
		GetWaterRecoveryData();
		GetWaterZeroCheckData();
		GetWaterSpanCheckData();
	}
	
	public void GetWaterCheckData(){
//		List<CheckData> list = new ArrayList<>();
		if(redisUtil==null) {
			System.out.println("redis为空，请联系管理员！");
			logger.error("redis为空，请联系管理员！");
			return;
		}
		while(redisUtil.lGetListSize("checkData")>0) {
			CheckData data = (CheckData)redisUtil.leftPop("checkData");
			System.out.println("获取到核查数据MN："+data.getMn());
			try {
				iCheckDataRepository.saveAndFlush(data);
			} catch (Exception e) {
				System.out.println("重复核查数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
				logger.error("重复核查数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
			}
//			list.add(data);
		}
//		iCheckDataRepository.saveAll(list);//该方法存在事务，不适合
	}
	
	public void GetWaterRecoveryData(){
//		List<RecoveryData> list = new ArrayList<>();
		if(redisUtil==null) {
			System.out.println("redis为空，请联系管理员！");
			logger.error("redis为空，请联系管理员！");
			return;
		}
		while(redisUtil.lGetListSize("recoveryData")>0) {
			RecoveryData data = (RecoveryData)redisUtil.leftPop("recoveryData");
			System.out.println("获取到加标回收率数据MN："+data.getMn());
			try {
				iRecoveryDataRepository.saveAndFlush(data);
			} catch (Exception e) {
				System.out.println("重复加标回收率数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
				logger.error("重复加标回收率数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
			}
//			list.add(data);
		}
//		iRecoveryDataRepository.saveAll(list);
	}
	
	public void GetWaterZeroCheckData(){
//		List<ZeroCheckData> list = new ArrayList<>();
		if(redisUtil==null) {
			System.out.println("redis为空，请联系管理员！");
			logger.error("redis为空，请联系管理员！");
			return;
		}
		while(redisUtil.lGetListSize("zeroCheckData")>0) {
			ZeroCheckData data = (ZeroCheckData)redisUtil.leftPop("zeroCheckData");
			System.out.println("获取到零点核查数据MN："+data.getMn());
			try {
				iZeroCheckDataRepository.saveAndFlush(data);
			} catch (Exception e) {
				System.out.println("重复零点核查数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
				logger.error("重复零点核查数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
			}
//			list.add(data);
		}
//		iZeroCheckDataRepository.saveAll(list);
	}
	
	public void GetWaterSpanCheckData(){
//		List<SpanCheckData> list = new ArrayList<>();
		if(redisUtil==null) {
			System.out.println("redis为空，请联系管理员！");
			logger.error("redis为空，请联系管理员！");
			return;
		}
		while(redisUtil.lGetListSize("spanCheckData")>0) {
			SpanCheckData data = (SpanCheckData)redisUtil.leftPop("spanCheckData");
			System.out.println("获取到跨度核查数据MN："+data.getMn());
			try {
				iSpanCheckDataRepository.saveAndFlush(data);
			} catch (Exception e) {
				System.out.println("重复跨度核查数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
				logger.error("重复跨度核查数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
			}
//			list.add(data);
		}
//		iSpanCheckDataRepository.saveAll(list);
	}
	
	public void GetWaterEquipmentInfo(){
		if(redisUtil==null) {
			System.out.println("redis为空，请联系管理员！");
			logger.error("redis为空，请联系管理员！");
			return;
		}
		List<EquipmentInfo> list = new ArrayList<>();
		while(redisUtil.lGetListSize("equipmentInfo")>0) {
			EquipmentInfo data = (EquipmentInfo)redisUtil.leftPop("equipmentInfo");
			System.out.println("获取到设备信息数据MN："+data.getMn());
			try {
				iEquipmentInfoRepository.saveAndFlush(data);
			} catch (Exception e) {
				System.out.println("重复设备信息数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
				logger.error("重复设备信息数据：mn="+data.getMn()+"factorCode="+data.getFactorCode()+"dateTime="+data.getDataTime());
			}
			list.add(data);
		}
//		iEquipmentInfoRepository.saveAll(list);
		saveUpdateRealEquipmentInfo(list);
	}
	
	/** 保存或更新实时设备信息 仪器参数，日志等 **/
	public void saveUpdateRealEquipmentInfo(List<EquipmentInfo> list) {
	    List<RealEquipmentInfo> realList = iRealEquipmentInfoRepository.findAll();
	    Map<String, RealEquipmentInfo> realMap = new HashMap<>();
	    String mn, indexCode, code, key;
	    for (RealEquipmentInfo realEquipmentInfo : realList) {
	        mn = realEquipmentInfo.getMn();
	        indexCode = realEquipmentInfo.getFactorCode();
	        code = realEquipmentInfo.getCode();
	        key = mn +"_" +indexCode+"_"+code;
	        if(realMap.get(key) == null) {
	            realMap.put(key, realEquipmentInfo);
	        }
        }
	    
	    Map<String, RealEquipmentInfo> saveMap = new HashMap<>();
	    Map<String, RealEquipmentInfo> updateMap = new HashMap<>();
	    RealEquipmentInfo real = null;
	    long time = 0L;
	    for (EquipmentInfo equipmentInfo : list) {
            mn = equipmentInfo.getMn();
            indexCode = equipmentInfo.getFactorCode();
            code = equipmentInfo.getCode();
            key = mn +"_" +indexCode+"_"+code;
            time = equipmentInfo.getDataTime().getTime();
            if(realMap.get(key) == null) {
                real = new RealEquipmentInfo();
                real.setCode(code);
                real.setMn(mn);
                real.setFactorCode(indexCode);
                if(saveMap.get(key) != null && saveMap.get(key).getDataTime().getTime() < time) {
                    saveMap.put(key, real);
                }else if(saveMap.get(key) == null ) {
                    saveMap.put(key, real);
                }
                
            }else {
                real = realMap.get(key);
                if(updateMap.get(key) != null && updateMap.get(key).getDataTime().getTime() < time) {
                    updateMap.put(key, real);
                }else if(updateMap.get(key) == null ) {
                    updateMap.put(key, real);
                }
            }
            real.setDataTime(equipmentInfo.getDataTime());
            real.setInfo(equipmentInfo.getInfo());
            real.setExplain(equipmentInfo.getExplain());
        }
	    iDataBatchRepository.batchSave(saveMap.values());
	    iDataBatchRepository.batchUpdate(updateMap.values());
	    
	}
	
	/**
	 * 保存实时数据
	 */
	public void saveRtd(){
		
		
		
	}
	
	
}
